import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:katana_router/katana_router.dart';
import 'package:sign_in_with_apple/sign_in_with_apple.dart';
import 'package:thal/backstage/toolkit/utilities/app_constants.dart';
import 'package:thal/backstage/toolkit/utilities/asset_manifest.dart';
import 'package:thal/backstage/toolkit/utilities/color_palette.dart';
import 'package:thal/backstage/toolkit/utilities/dimension_rules.dart';
import 'package:thal/backstage/toolkit/widgets/common_utils.dart';
import 'package:thal/backstage/toolkit/widgets/loading_indicator.dart';
import 'package:thal/backstage/toolkit/widgets/stage_whisper.dart';
import 'package:thal/playbill/auth_sage/register_production.dart';
import 'package:thal/backstage/control_room/global_state_provider.dart';

part 'login_production.page.dart';

/// 登录页面
@PagePath('/login')
class LoginProduction extends StatefulWidget {
  const LoginProduction({super.key});

  @pageRouteQuery
  static const query = _$LoginProductionQuery();

  @override
  State<LoginProduction> createState() => _LoginProductionState();
}

class _LoginProductionState extends State<LoginProduction> {
  final _usernameTextInput = TextEditingController();
  final _passwordTextInput = TextEditingController();

  @override
  void dispose() {
    _usernameTextInput.dispose();
    _passwordTextInput.dispose();
    super.dispose();
  }

  /// 处理登录逻辑
  Future<void> _initiateAuthentication() async {
    final username = _usernameTextInput.text.trim();
    final password = _passwordTextInput.text.trim();

    if (username.isEmpty) {
      StageWhisper.caution('Please enter username');
      return;
    }

    if (password.isEmpty) {
      StageWhisper.caution('Please enter password');
      return;
    }

    LoadingCurtain.raiseCurtain(message: 'Logging in...');

    // 使用全局状态管理
    final userRoom = GlobalStateProvider.userRoomOf(context);
    final checkInRoom = GlobalStateProvider.checkInRoomOf(context);

    // 执行登录验证
    final loginSuccess = userRoom.performLogin(username, password);

    await Future.delayed(const Duration(seconds: 1));
    LoadingCurtain.lowerCurtain();

    if (loginSuccess) {
      // 登录成功后自动打卡
      final currentUser = userRoom.fetchCurrentUser();
      if (currentUser != null) {
        final checkInSuccess = checkInRoom.performCheckIn(currentUser.id);
        if (checkInSuccess) {
          StageWhisper.cheer('Login successful! Check-in completed!');
        } else {
          StageWhisper.cheer('Login successful! Already checked in today.');
        }
      } else {
        StageWhisper.cheer('Login successful!');
      }

      // 登录成功后跳转到主页
      Navigator.of(context).pop();
    } else {
      StageWhisper.lament('Invalid username or password');
    }
  }

  /// 跳转到注册页面
  Future<void> _navigateToRegistration() async {
    final result = await context.router.push(RegisterProduction.query());

    // 如果注册成功，自动填入账号密码
    if (result != null && result is Map<String, dynamic>) {
      final account = result['account'] as String?;
      final password = result['password'] as String?;

      if (account != null) {
        _usernameTextInput.text = account;
      }
      if (password != null) {
        _passwordTextInput.text = password;
      }

      // 显示提示信息
      if (account != null && password != null) {
        StageWhisper.cheer('Account created! Please login.');
      }
    }
  }

  /// Apple 登录
  Future<void> _performAppleSignIn() async {
    LoadingCurtain.raiseCurtain(message: 'Signing in...');

    try {
      final credential = await SignInWithApple.getAppleIDCredential(
        scopes: [
          AppleIDAuthorizationScopes.email,
          AppleIDAuthorizationScopes.fullName,
        ],
      );

      // 使用全局状态管理
      final userRoom = GlobalStateProvider.userRoomOf(context);
      final checkInRoom = GlobalStateProvider.checkInRoomOf(context);

      // 生成用户名（使用Apple提供的姓名或默认名称）
      String username = 'Apple User';
      if (credential.givenName != null && credential.familyName != null) {
        username = '${credential.givenName} ${credential.familyName}';
      } else if (credential.givenName != null) {
        username = credential.givenName!;
      }

      // 生成账号（使用Apple ID或生成唯一ID）
      String account =
          credential.userIdentifier ??
          'apple_${DateTime.now().millisecondsSinceEpoch}';

      // 生成密码（使用Apple的授权码）
      String password = '123456';

      // 检查用户是否已存在
      final existingUser = userRoom.fetchUserByAccount(account);

      if (existingUser == null) {
        // 注册新用户
        final registerSuccess = userRoom.performRegister(
          account: account,
          password: password,
          username: username,
          birthDate: DateTime.now(), // 使用注册日期作为出生日期
          signature: 'Welcome to the lake community!', // 默认签名
          avatar: 'assets/images/avatar1.png', // 默认头像
        );

        if (registerSuccess) {
          StageWhisper.cheer('Apple Sign In successful! Welcome!');
        } else {
          StageWhisper.lament('Apple Sign In failed');
          LoadingCurtain.lowerCurtain();
          return;
        }
      } else {
        // 用户已存在，直接登录
        final loginSuccess = userRoom.performLogin(account, password);
        if (!loginSuccess) {
          StageWhisper.lament('Apple Sign In failed');
          LoadingCurtain.lowerCurtain();
          return;
        }
      }

      // 登录成功后自动打卡
      final currentUser = userRoom.fetchCurrentUser();
      if (currentUser != null) {
        final checkInSuccess = checkInRoom.performCheckIn(currentUser.id);
        if (checkInSuccess) {
          // StageWhisper.cheer('Check-in completed!');
        }
      }

      LoadingCurtain.lowerCurtain();

      // 返回上一个页面
      Navigator.of(context).pop();
    } catch (e) {
      LoadingCurtain.lowerCurtain();
      StageWhisper.lament('Apple Sign In failed');
    }
  }

  /// 打开服务条款
  void _openTermsOfService() {
    CommonUtils.launchUrl(ProjectConstants.termsOfServiceUrl);
  }

  /// 打开隐私政策
  void _openPrivacyPolicy() {
    CommonUtils.launchUrl(ProjectConstants.privacyPolicyUrl);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      resizeToAvoidBottomInset: false,
      body: Container(
        width: double.infinity,
        height: double.infinity,
        decoration: BoxDecoration(
          image: DecorationImage(
            image: AssetImage(AssetManifest.splashBackground),
            fit: BoxFit.cover,
          ),
        ),
        child: SafeArea(
          bottom: false,
          child: Column(
            children: [
              // 顶部导航栏
              _buildTopNavigationBar(),

              // Logo 区域
              Expanded(child: Center(child: _buildLogoSection())),

              // 登录表单卡片（固定在底部）
              _buildAuthenticationCard(),
            ],
          ),
        ),
      ),
    );
  }

  /// 构建顶部导航栏
  Widget _buildTopNavigationBar() {
    return Padding(
      padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 12.h),
      child: Row(
        children: [
          // 返回按钮
          GestureDetector(
            onTap: () => Navigator.of(context).pop(),
            child: Container(
              width: 40.w,
              height: 40.w,
              decoration: BoxDecoration(
                color: ColorPalette.iconBg,
                shape: BoxShape.circle,
              ),
              child: Icon(
                Icons.chevron_left_rounded,
                color: ColorPalette.black,
                size: 30.sp,
              ),
            ),
          ),
          12.w.widthBox,
          Text(ProjectConstants.appName)
              .fontSize(24.sp)
              .textColor(ColorPalette.black)
              .arimo(weight: FontWeight.bold),
        ],
      ),
    );
  }

  /// 构建 Logo 区域
  Widget _buildLogoSection() {
    return Container(
      width: 100.w,
      height: 100.w,
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(24.r),
        border: Border.all(color: ColorPalette.white, width: 5.w),
        boxShadow: [
          BoxShadow(
            color: ColorPalette.blue1.withValues(alpha: 0.3),
            blurRadius: 20,
            spreadRadius: 2,
          ),
        ],
      ),
      child: ClipRRect(
        borderRadius: BorderRadius.circular(24.r),
        child: Image.asset(AssetManifest.logo, fit: BoxFit.cover),
      ),
    );
  }

  /// 构建登录表单卡片
  Widget _buildAuthenticationCard() {
    return Container(
      constraints: BoxConstraints(maxHeight: 600.h),
      padding: EdgeInsets.fromLTRB(24.w, 32.h, 24.w, 24.h),
      decoration: BoxDecoration(
        color: ColorPalette.inputBg,
        borderRadius: BorderRadius.only(
          topLeft: Radius.circular(24.r),
          topRight: Radius.circular(24.r),
        ),
        boxShadow: [
          BoxShadow(
            color: ColorPalette.black.withValues(alpha: 0.1),
            blurRadius: 20,
            offset: Offset(0, -4.h),
          ),
        ],
      ),
      child: SingleChildScrollView(
        physics: const ClampingScrollPhysics(),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: [
            // 标题
            Center(
              child: Text('Welcome to log in')
                  .fontSize(26.sp)
                  .textColor(ColorPalette.blue1)
                  .arimo(weight: FontWeight.bold),
            ),

            32.h.heightBox,

            // 用户名输入框
            _buildInputField(
              controller: _usernameTextInput,
              label: 'username',
              hintText: 'Enter your username',
              isPassword: false,
            ),

            20.h.heightBox,

            // 密码输入框
            _buildInputField(
              controller: _passwordTextInput,
              label: 'password',
              hintText: 'password',
              isPassword: true,
            ),

            20.h.heightBox,

            // 注册提示
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Text(
                  "Don't have an account? ",
                ).fontSize(13.sp).textColor(ColorPalette.black),
                GestureDetector(
                  onTap: _navigateToRegistration,
                  child: Text(
                    'Sign up',
                    style: TextStyle(
                      fontSize: 13.sp,
                      color: ColorPalette.black,
                      fontWeight: FontWeight.w600,
                      decoration: TextDecoration.underline,
                    ),
                  ),
                ),
              ],
            ),

            24.h.heightBox,

            // 登录按钮
            _buildLoginButton(),

            24.h.heightBox,

            // 分割线
            Row(
              children: [
                Expanded(child: Divider(color: ColorPalette.grey)),
                Padding(
                  padding: EdgeInsets.symmetric(horizontal: 12.w),
                  child:
                      Text(
                        'Or continue with',
                      ).fontSize(12.sp).textColor(ColorPalette.black).arimo(),
                ),
                Expanded(child: Divider(color: ColorPalette.grey)),
              ],
            ),

            24.h.heightBox,

            // Apple 登录按钮
            _buildAppleSignInButton(),

            24.h.heightBox,

            // 服务条款
            _buildTermsSection(),
          ],
        ),
      ),
    );
  }

  /// 构建输入框
  Widget _buildInputField({
    required TextEditingController controller,
    required String label,
    required String hintText,
    required bool isPassword,
  }) {
    return Stack(
      children: [
        Container(
          margin: EdgeInsets.only(top: 8.h),
          decoration: BoxDecoration(
            color: ColorPalette.inputBg,
            borderRadius: BorderRadius.circular(12.r),
            border: Border.all(color: ColorPalette.grey, width: 1),
          ),
          child: TextField(
            controller: controller,
            obscureText: isPassword,
            style: TextStyle(fontSize: 15.sp, color: ColorPalette.black),
            textInputAction: TextInputAction.done,
            decoration: InputDecoration(
              hintText: hintText,
              hintStyle: TextStyle(
                fontSize: 15.sp,
                color: ColorPalette.black.withValues(alpha: 0.3),
              ),
              border: InputBorder.none,
              contentPadding: EdgeInsets.symmetric(
                horizontal: 16.w,
                vertical: 14.h,
              ),
            ),
          ),
        ),
        Positioned(
          left: 12.w,
          top: 0,
          child: Container(
            padding: EdgeInsets.symmetric(horizontal: 4.w),
            color: ColorPalette.inputBg,
            child:
                Text(label)
                    .fontSize(12.sp)
                    .textColor(ColorPalette.black.withValues(alpha: 0.6))
                    .arimo(),
          ),
        ),
      ],
    );
  }

  /// 构建登录按钮
  Widget _buildLoginButton() {
    return Container(
      height: 50.h,
      decoration: BoxDecoration(
        gradient: LinearGradient(
          colors: [ColorPalette.blue1, ColorPalette.blue1],
        ),
        borderRadius: BorderRadius.circular(12.r),
        boxShadow: [
          BoxShadow(
            color: ColorPalette.blue1.withValues(alpha: 0.3),
            blurRadius: 12,
            offset: Offset(0, 4.h),
          ),
        ],
      ),
      child: Material(
        color: Colors.transparent,
        child: Center(
          child: Text('Log In')
              .fontSize(16.sp)
              .textColor(ColorPalette.white)
              .arimo(weight: FontWeight.bold),
        ),
      ),
    ).withTapEffect(onTap: _initiateAuthentication);
  }

  /// 构建 Apple 登录按钮
  Widget _buildAppleSignInButton() {
    return Center(
      child: GestureDetector(
        onTap: _performAppleSignIn,
        child: Container(
          width: 60.w,
          height: 60.w,
          decoration: BoxDecoration(
            color: ColorPalette.white,
            shape: BoxShape.circle,
            border: Border.all(color: ColorPalette.grey, width: 1),
          ),
          child: Center(
            child: Icon(Icons.apple, size: 32.sp, color: ColorPalette.black),
          ),
        ),
      ),
    );
  }

  /// 构建服务条款区域
  Widget _buildTermsSection() {
    return FittedBox(
      fit: BoxFit.scaleDown,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Text('By Continuing you agree with ')
              .fontSize(11.sp)
              .textColor(ColorPalette.black.withValues(alpha: 0.6)),
          GestureDetector(
            onTap: _openTermsOfService,
            child: Text(
              'Terms of Service',
              style: TextStyle(
                fontSize: 11.sp,
                color: ColorPalette.black,
                fontWeight: FontWeight.w600,
                decoration: TextDecoration.underline,
              ),
            ),
          ),
          Text(' & ')
              .fontSize(11.sp)
              .textColor(ColorPalette.black.withValues(alpha: 0.6)),
          GestureDetector(
            onTap: _openPrivacyPolicy,
            child: Text(
              'Privacy Policy',
              style: TextStyle(
                fontSize: 11.sp,
                color: ColorPalette.black,
                fontWeight: FontWeight.w600,
                decoration: TextDecoration.underline,
              ),
            ),
          ),
        ],
      ),
    );
  }
}
